/**
 * 并发请求队列库
 * @param {Array} paramsList - 请求参数数组
 * @param {Function} requestFunc - 异步请求函数 (param) => Promise
 * @param {Object} [options] - 配置选项
 * @param {number} [options.maxConcurrent=4] - 最大并发数
 * @param {boolean} [options.stopOnError=false] - 遇到错误是否停止
 * @returns {Promise<Array>} - 返回结果数组，格式同Promise.allSettled
 */
export function createConcurrentQueue(paramsList, requestFunc, options = {}) {
    // 参数校验
    if (!Array.isArray(paramsList)) {
        throw new TypeError('paramsList must be an array');
    }
    if (typeof requestFunc !== 'function') {
        throw new TypeError('requestFunc must be a function');
    }

    // 合并配置
    const {
        maxConcurrent = 4, stopOnError = false
    } = options;

    return new Promise((resolve) => {
        // 处理空队列
        if (paramsList.length === 0) return resolve([]);

        const results = new Array(paramsList.length).fill(null);
        const queue = paramsList.map((param, index) => ({
            param,
            index
        }));
        let activeCount = 0;
        let hasError = false;
        let completedCount = 0;

        // 处理队列任务
        const processQueue = () => {
            // 停止条件：队列空/错误停止/所有任务完成
            if (queue.length === 0 || activeCount >= maxConcurrent || hasError) return;

            const {
                param,
                index
            } = queue.shift();
            activeCount++;

            requestFunc(param)
                .then(result => {
                    results[index] = {
                        status: 'fulfilled',
                        value: result
                    };
                })
                .catch(error => {
                    results[index] = {
                        status: 'rejected',
                        reason: error
                    };
                    if (stopOnError) hasError = true;
                })
                .finally(() => {
                    activeCount--;
                    completedCount++;

                    // 所有任务完成
                    if (completedCount === paramsList.length) {
                        resolve(results);
                    }
                    // 继续处理队列
                    else if (!hasError) {
                        processQueue();
                    }
                });

            // 继续填充并发槽位
            processQueue();
        };

        // 初始启动（填充并发槽位）
        for (let i = 0; i < Math.min(maxConcurrent, paramsList.length); i++) {
            processQueue();
        }
    });
}

// 默认导出
export default createConcurrentQueue;